package com.shrfid.rfidsdk.tag.hf;




import com.shrfid.rfidsdk.tag.base.BaseResponseFrame;
import com.shrfid.rfidsdk.uitls.ReadTagUtils;

import java.nio.ByteBuffer;
import java.util.Arrays;




/**
 * 响应数据帧¬
 */
public class HFResponseFrame extends BaseResponseFrame {

    public byte sof;                                       //帧头
    public byte rollCode;                                   //滚码,0xff代表广播
    public byte[] cmd;                                      //cmd

    public byte getSof() {
        return sof;
    }

    public void setSof(byte sof) {
        this.sof = sof;
    }

    public byte getLen() {
        return len;
    }

    public void setLen(byte len) {
        this.len = len;
    }

    public byte getRollCode() {
        return rollCode;
    }

    public void setRollCode(byte rollCode) {
        this.rollCode = rollCode;
    }

    public byte[] getCmd() {
        return cmd;
    }

    public void setCmd(byte[] cmd) {
        this.cmd = cmd;
    }

    public byte[] toBytes() {
        ByteBuffer buffer = ByteBuffer.allocate(len + 1);//长度不包括sof,所以这里要+1
        buffer.put(sof);
        buffer.put(len);
        buffer.put(rollCode);
        buffer.put(cmd);
        buffer.put(status);
        if (params != null) {
            buffer.put(params);
        }
        buffer.put(crc);
        return buffer.array();
    }

    /**
     * 根据滚码+命令生成key作为查询返回结果的索引
     *
     * @return key
     */
    public String generateKey() {
        ByteBuffer buffer = ByteBuffer.allocate(3);
        buffer.put(rollCode);
        buffer.put(cmd);
        return ReadTagUtils.bytesToHexString(buffer.array());
    }

    @Override
    public String toString() {
        return ReadTagUtils.bytesToFormatHexString(toBytes());
    }

    /**
     * 通过CRC校验自己数据是否正常
     * 只有数据都填充完了再条用才有效
     *
     * @return
     */
    public boolean checkSelf() {
        boolean ret = false;
        try {
            ByteBuffer buffer = ByteBuffer.allocate(len - 2);
            buffer.put(len);
            buffer.put(rollCode);
            buffer.put(cmd);
            buffer.put(status);
            if (params != null) {
                buffer.put(params);
            }
            byte[] bytes = ReadTagUtils.calCrc16(buffer.array());

            ret = Arrays.equals(bytes, crc);
            if (ret) {
//                Logger.d("CRC校验成功,计算出的CRC:" + bytesToHexString(bytes) + "  实际CRC:" + bytesToHexString(crc));
            }else{
//                Logger.d("CRC校验失败,计算出的CRC:" + bytesToHexString(bytes) + "  实际CRC:" + bytesToHexString(crc));
            }        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
}
